package org.zjt.demo.config;


import lombok.Data;
import org.apache.http.util.Asserts;
import org.quartz.Job;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.zjt.demo.annotation.QuartzJob;
import org.zjt.demo.config.properties.JobProperties;

import java.util.LinkedList;
import java.util.List;

/**
 * @author <a href="juntao.zhang@bkjk.com">juntao.zhang</a>
 * @Description:
 * @Package com.bkjk.platform.uc.web.config
 * @date 2018/4/3 16:25
 * @see
 */

@Data
public class QuartzJobLoader implements BeanPostProcessor {

    private QuartzProperties quartzProperties = new QuartzProperties(new LinkedList());

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        if(aClass.isAnnotationPresent(QuartzJob.class) ){
            Asserts.check(Job.class.isAssignableFrom(aClass), aClass + " is not implements "+ Job.class);
            QuartzJob annotation = aClass.getAnnotation(QuartzJob.class);
            List<JobProperties> jobs = quartzProperties.getJobs();
            JobProperties jobProperties = new JobProperties();
            jobProperties.setClazz(aClass.getName());
            jobProperties.setCron(annotation.cron());
            jobProperties.setId(annotation.id());
            jobProperties.setDelay(annotation.delay());
            jobs.add(jobProperties);

        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
